import qs from "qs";

const apiUrl = process.env.REACT_APP_API_URL;

export const http = async (endpoint, data, ...customConfig) => {
  const config = {
    method: "GET",
    ...customConfig,
  };
  if (config.method.toUpperCase() === "GET") {
    endpoint += `?${qs.stringify(data)}`;
  } else {
    config.body = JSON.stringify(data || {});
  }
  return window
    .fetch(`${apiUrl}/${endpoint}`, config)
    .then(async (response) => {
      if (response.status === 500) {
        return Promise.reject({ message: response.statusText });
      }
      const data = await response.json();
      if (response.ok) {
        return data;
      } else {
        return Promise.reject(response.statusText);
      }
    });
};